package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.model.product.SpuImage;
import com.atguigu.gmall.model.product.SpuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.model.product.SpuSaleAttrValue;
import com.atguigu.gmall.product.service.SpuImageService;
import com.atguigu.gmall.product.service.SpuSaleAttrService;
import com.atguigu.gmall.product.service.SpuSaleAttrValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.product.service.SpuInfoService;
import com.atguigu.gmall.product.mapper.SpuInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 24440
* @description 针对表【spu_info(商品表)】的数据库操作Service实现
* @createDate 2022-08-23 18:02:00
*/
@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo>
    implements SpuInfoService{

    @Resource
    private SpuInfoMapper spuInfoMapper;
    @Resource
    private SpuImageService spuImageService;
    @Resource
    private SpuSaleAttrService spuSaleAttrService;
    @Resource
    private SpuSaleAttrValueService spuSaleAttrValueService;
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1.把spu的基本信息保存到spu_info表中
        spuInfoMapper.insert(spuInfo);

        Long id = spuInfo.getId();
        //保存销售属性名到spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
            //回填spuID
            spuSaleAttr.setSpuId(id);
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            //保存销售属性值到spu_sale_attr_value 中
            for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                spuSaleAttrValue.setSpuId(id);
                String saleAttrName = spuSaleAttr.getSaleAttrName();
                spuSaleAttrValue.setSaleAttrName(saleAttrName);
            }
            spuSaleAttrValueService.saveBatch(spuSaleAttrValueList);
        }
        spuSaleAttrService.saveBatch(spuSaleAttrList);
        //把spu的图片保存到spu——image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        for (SpuImage spuImage : spuImageList) {
            spuImage.setSpuId(id);
        }
        spuImageService.saveBatch(spuImageList);
    }
}




